package eva.savant.business.ventas.view

import eva.savant.businessobject.vt.Vendedor
import eva.savant.businessobject.vt.Venta

import javax.faces.bean.ManagedBean
import javax.faces.bean.SessionScoped
import javax.annotation.PostConstruct
import javax.faces.convert.Converter
import org.primefaces.model.chart.AxisType
import org.primefaces.model.chart.ChartSeries
import org.primefaces.model.chart.CategoryAxis
import org.primefaces.model.chart.LineChartModel

@SessionScoped
@ManagedBean(name = 'IIVentasDiarioChart')
public class IIVentasDiarioChart extends Bean {

  Date dateIni, dateEnd

  def model

  @PostConstruct
  public void cleanEntity() {

    model=  null

    lsEntity = null

    entity = new Venta()

    dateIni= dateEnd= new Date()
  }

  public List findLsEntity() { model= null

    dateIni= toStartDay(dateIni); dateEnd= toMidnight(dateEnd); form= true


    def q= entity.vendedor?.id != null? 'and vendedor.id=?' : ''

    def qA= "sum(importe), sum(descuento), sum(total): operacionId > 0 and fecha between ? and ? ${q}"

    def qB= "fecha, sum(importe), sum(descuento), sum(total): operacionId > 0 and fecha between ? and ? ${q} group by fecha order by fecha"


    def    d= entity.vendedor?.id != null?  get(Venta, qA, dateIni, dateEnd, entity.vendedor?.id) :  get(Venta, qA, dateIni, dateEnd)

    lsEntity= entity.vendedor?.id != null? find(Venta, qB, dateIni, dateEnd, entity.vendedor?.id) : find(Venta, qB, dateIni, dateEnd)


    entity.importe= d[0]; entity.descuento= d[1]; entity.total= d[2]

    buildChart(); return lsEntity
  }

  public buildChart() {

    model = new LineChartModel()

    model.setLegendPosition('n')

    model.setShowPointLabels(true)

    model.getAxes().put(AxisType.X, new CategoryAxis('Fecha'))

    model.getAxis(AxisType.Y).setLabel('Importe')

    model.getAxis(AxisType.X).setTickAngle(90)


    def c= new ChartSeries()

    c.setLabel 'Total Ventas Diario'

    for(x in lsEntity) c.set x[0].format('dd.M'), x[3]

    model.addSeries c
  }

  public List complete(String value) { return completeLike(Vendedor.class,'persona.nombre',value) }

  public Converter getConverter() { return converterLike(Vendedor.class) }

}

